#include <stdint.h>
#include <string.h>

#include "main.h"
#include "spi.h"
#include "dma.h"

#include "fx_power.h"
#include "fx_gpio.h"
#include "fx_spi.h"
#include "fx_frame.h"

#include "aoaoutil.h"
#include "rtthread.h"

void log_wrdata(uint32_t *wdata, uint32_t *rdata, uint16_t len)
{
    for (uint16_t i = 0; i < len; i++)
    {
        rt_kprintf("0x%08X", wdata[i]);
        if (i != len - 1)
        {
            rt_kprintf(", ");
        }
    }

    rt_kprintf("\n");

    for (uint16_t i = 0; i < len; i++)
    {
        rt_kprintf("0x%08X", rdata[i]);
        if (i != len - 1)
        {
            rt_kprintf(", ");
        }
    }

    rt_kprintf("\n");
}

void fx_frame_execute(fx_frame_t *frame)
{
    if (frame->prefix_callback != NULL)
    {
        frame->prefix_callback(frame);
    }

    rt_thread_mdelay(frame->prefix_delay_us / 1000);

    uint8_t write_buffer[4] = {0};
    uint8_t read_buffer[4] = {0};

    for (size_t n = 0; n < frame->data_num; n++)
    {
        aut_afromu32_be(write_buffer, frame->write_data[n]);
        HAL_SPI_TransmitReceive_DMA(&hspi1, write_buffer, read_buffer, 4);
        while (HAL_SPI_GetState(&hspi1) == HAL_SPI_STATE_BUSY_TX_RX)
        {
            ;
        }
        if (n != (frame->data_num - 1))
        {
            rt_thread_mdelay(frame->data_interval_us / 1000);
        }
        frame->read_data[n] = aut_atou32_be(read_buffer);
    }

    if (frame->suffix_callback != NULL)
    {
        frame->suffix_callback(frame);
    }

    rt_thread_mdelay(frame->suffix_delay_us / 1000);
}
